/******
附件上传和选择

<attachment owner-id="111" owner-type="222" sub-owner-id="11222" dhf-ng-model="abc" xtype="obj" mult="false"></attachment>
如果：owner-id 和 owner-type不传入，则不能上传附件，只能选择附件
owner-id 是所属 对象的id。例如：如果是商品，那么就是商品的id；如果是入库单，就是入库单的id
owner-type 是类型：商品附件=item，入库单=stock，如果不够，找我继续这里补充。自己不能随便定义。
sub-owner-id 子对象id
setback 窗口关闭回调函数，格式：function(attach){.....}
hideList: 是否隐藏列表

dhf-ng-model 父页面参数，选择附件 点击确定后会 数据自动同步到该参数
xtype返回的数据类型，当单选时该参数有效，url=直接返回附件url路径，非url=返回附件obj对象

mult是否允许多选，true=多选按钮，可以选择多个附件，返回附件的数组对象；非true=单选按钮，只能返回1个附件
****/

(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:attachment
     * @description
     * # attachment
     */
    angular.module('webApp')
        //调用其他方法
        .run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.attachment.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive('attachment', function() {
            return {
                restrict: 'E',
                template: "<a href='javascript:void(0);' class={{class}} ng-click='choseAttach();'>{{title|translate}}</a>",
                scope: {
                    ownerId: '=', //所属对象id
                    ownerType: '@', //所属类型：item、stock等
                    subOwnerId: '=', //所属子对象id
                    dhfNgModel: '=', //绑定的model
                    xtype: '@', //返回类型: url=返回附件url地址，obj=返回附件对象
                    mult: "@", //是否允许多选
                    title: "@", //按钮文字
                    setback: "&", //回调函数
                    hideList: "@", //是否隐藏列表
                    useType: "@", //选择使用文件类型如图片为image
                    maxSize: "@", //单个文件最大值
                    checkbox: "@",
                    xclass: "@"
                },

                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout) {
                        // $scope.class = $scope.xclass ? $scope.xclass : "sui-btn  btn-success";
                        $scope.allTypes = $scope.useType ? $scope.useType.split(",") : [];
                        // $scope.checkedAttach = [];
                        var showDialog = null;
                        // pages/order/confirm/index
                        function allow(type) {
                            if (!$scope.useType) {
                                return true;
                            } else {
                                return $scope.allTypes.indexOf(type) != -1;
                            }
                        }

                        $scope.chosedClass = function(attach) {
                            var value = false;
                            _.map($scope.checkedAttach, function(one, key) {
                                if (one.id == attach.id) {
                                    value = one.id;
                                }
                            });

                            return value;
                        }

                        $scope.choseAttach = function() {
                            if (!$scope.hideList) {
                                $scope.attachList().then(showPop);
                            } else {
                                showPop();
                            }
                        }

                        $scope.title = $scope.title || "attachment";

                        $scope.clickcheck = function(envet, one, type) {
                            console.error("one", one);
                            if (!allow(one.original_name.substring(one.original_name.lastIndexOf('.') + 1))) {
                                return;
                            }

                            var value = false;
                            if ($scope.checkbox) {
                                if ($scope.checkedAttach.length) {
                                    _.map($scope.checkedAttach, function(da, key) {
                                        if (da.$$hashKey == one.$$hashKey) {
                                            $scope.checkedAttach.splice(key, 1);
                                            value = 1;
                                        }
                                    });
                                }
                            } else {
                                $scope.checkedAttach = [];
                            }

                            if (!value) {
                                $scope.checkedAttach.push(one);
                            }

                            if (type) {
                                $scope.setdata();
                                showDialog.hide();
                                rmbdbg();
                            }
                        }

                        function showPop() {
                            $scope.checkedAttach = [];
                            showDialog = $.alert({
                                backdrop: 'static',
                                keyboard: true,
                                title: '<span>+{{"attachment" | translate}}</span>',
                                body: $templateCache.get("views/directives.attachment.html"),
                                okBtn: '{{"ok" | translate}}',
                                closeBtn: true,
                                transition: true,
                                // hasfoot: false,
                                width: '880px',
                                show: function(e) {
                                    $compile($(e.currentTarget).contents())($scope);
                                    return true;
                                },
                                okHide: function(e) {
                                    $scope.setdata();
                                },
                            });
                        }

                        $scope.setdata = function() {
                            $timeout(function() {
                                if ($scope.checkbox) {
                                    $scope.dhfNgModel = $scope.checkedAttach;
                                } else {
                                    //返回数据 
                                    if ($scope.mult == 'true') {
                                        $scope.dhfNgModel = $scope.checkedAttach[0];
                                    } else {
                                        if ($scope.checkedAttach && $scope.xtype == 'url') {
                                            if ($scope.checkedAttach[0]) {
                                                $scope.dhfNgModel = $scope.checkedAttach[0].path;
                                            }
                                        } else {
                                            $scope.dhfNgModel = $scope.checkedAttach[0];
                                        }
                                    }
                                }
                                if ($scope.setback) {
                                    $scope.setback({
                                        attach: $scope.dhfNgModel
                                    });
                                }

                            });
                        }

                        $scope.itemsTotal = 0;
                        $scope.pageSize = 10;
                        $scope.attachList = function(pageNo) {
                            if ($scope.hideList) {
                                setTimeout(function() {
                                    rmAlert();
                                }, 1000);
                            } else {
                                var query = {
                                    page_no: pageNo,
                                    page_size: $scope.pageSize,
                                    mime: $scope.useType,
                                };
                                return dataService.attachGet(query).then(function(list) {
                                    $scope.attachs = list.attachment;
                                    // console.error("dddddddddddddddd", $scope.attachs)
                                    $scope.itemsTotal = list.total_count;
                                });
                            }

                        }

                    }
                ],
                link: function(scope, element, attrs, ctrl) {
                    scope.class = attrs.xclass ? attrs.xclass : "sui-btn  btn-success";
                }
            }
        })
        .directive('attachmentlist', function() {
            return {
                restrict: 'E',
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                    useType: "@", //选择使用文件类型如图片为image

                },
                templateUrl: "views/directives.attachent.list.html",
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout) {
                        //                         console.error("ngModelngModelngModel", $scope.ngModel);
                        $scope.initData = function() {
                            if ($scope.tmpNgModel.id) {
                                $scope.tmpNgModel = [$scope.tmpNgModel];
                            }
                            _.map($scope.tmpNgModel, function(v, k) {
                                if (['jpg', 'png', 'gif', 'jpeg', 'mp4', 'JPG', 'PNG', 'GIF', 'JPEG'].indexOf(v.original_name.substring(v.original_name.lastIndexOf('.') + 1)) == -1 && v.mime != undefined) {
                                    $scope.tmpNgModel[k].isclass = "flies-" + v.original_name.split(".")[1];
                                } else if (v.mime == undefined) {
                                    $scope.tmpNgModel[k].isclass = "flies-" + v[k].mime;
                                }
                                // console.error(" $scope.tmpNgModel", $scope.tmpNgModel);
                            });
                        }
                    }
                ],
                link: function(scope, element, attrs, ctrl) {
                    ctrl.$render = function() {
                        if (ctrl.$viewValue) {
                            scope.tmpNgModel = ctrl.$viewValue;
                            scope.initData();
                        }
                    };
                }
            }
        })
        .run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.wxattachment.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive('wxAttachment', function() {
            return {
                restrict: 'E',
                template: "<a href='javascript:void(0);' class='{{class}}' ng-click='choseAttach();'>{{title|translate}}</a>",
                scope: {
                    wxappid: '=', //小程序id
                    // ownerType: '@', //所属类型：item、stock等
                    // subOwnerId: '=', //所属子对象id
                    dhfNgModel: '=', //绑定的model
                    xtype: '@', //返回类型: url=返回附件url地址，obj=返回附件对象
                    mult: "@", //是否允许多选
                    title: "@", //按钮文字
                    setback: "&", //回调函数
                    hideList: "@", //是否隐藏列表
                    useType: "@", //选择使用文件类型如图片为image
                    stype: "@",
                },

                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout) {
                        $scope.allTypes = $scope.useType ? $scope.useType.split(",") : [];
                        $scope.checkedAttach = {};

                        function allow(type) {
                            if (!$scope.useType) {
                                return true;
                            } else {
                                return $scope.allTypes.indexOf(type) != -1;
                            }
                        }
                        $scope.chosedClass = function(attach) {
                            // console.log("attach",attach);
                            return $scope.checkedAttach.media_id == attach.media_id;
                        }

                        $scope.choseAttach = function() {
                            if (!$scope.hideList) {
                                $scope.attachList().then(showPop);
                            } else {
                                showPop();
                            }
                        }


                        $scope.clickcheck = function(envet, one, type) {
                            if (!one) return;
                            $scope.checkedAttach = one;
                            if (type) {
                                $scope.setdata();

                            }
                        }

                        $scope.setdata = function() {
                            console.error(" $scope.dhfNgModel", $scope.dhfNgModel);
                            $timeout(function() {
                                if ($scope.checkedAttach && $scope.xtype == 'mid') {
                                    $scope.dhfNgModel = $scope.checkedAttach.media_id;
                                } else {
                                    $scope.dhfNgModel = $scope.checkedAttach;
                                }
                                if ($scope.setback) {
                                    $scope.setback({
                                        attach: $scope.dhfNgModel
                                    });
                                }
                                // rmAlert();
                            });
                        }

                        function showPop() {
                            $.alert({
                                backdrop: 'static',
                                keyboard: true,
                                title: '<span>{{title | translate}}</span>',
                                body: $templateCache.get("views/directives.wxattachment.html"),
                                okBtn: '{{"ok" | translate}}',
                                closeBtn: true,
                                transition: true,
                                // hasfoot: false,
                                width: '880px',
                                show: function(e) {
                                    $compile($(e.currentTarget).contents())($scope);
                                    return true;
                                },
                                okHide: function(e) {
                                    $scope.setdata();
                                    // rmAlert();
                                },
                            });
                        }

                        $scope.attachList = function(pageNo) {
                            var query = {};
                            if ($scope.wxappid) {
                                query.app_id = $scope.wxappid
                            }
                            return dataService.materialGet({ query: query }).then(function(list) {
                                $scope.attachs = list.materialRecords;
                                // console.log($scope.attachs)
                                $scope.itemsTotal = list.total_count;
                            });
                        }
                    }
                ],
                link: function(scope, element, attrs, ctrl) {
                    scope.class = attrs.xclass;
                }
            }
        })
        .run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.wxgzhurlattachment.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive('wxGzhUrlAttachment', function() {
            return {
                restrict: 'E',
                template: "<a href='javascript:void(0);' class='{{class}}' ng-click='choseAttach();'>{{title|translate}}</a>",
                scope: {
                    wxappid: '=', //公众号idid
                    dhfNgModel: '=', //绑定的model
                    xtype: '@', //返回类型: url=返回附件url地址，obj=返回附件对象
                    mult: "@", //是否允许多选
                    title: "@", //按钮文字
                    setback: "&", //回调函数
                    hideList: "@", //是否隐藏列表
                    useType: "@", //选择使用文件类型如图片为image
                    stype: "@",
                    xclass: "@",
                    tabtype: "@", //tab是否展示
                    datatype: "@",
                    chosedStatus: "@",
                },
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'sessionService',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, sessionService) {
                        $scope.allTypes = $scope.useType ? $scope.useType.split(",") : [];
                        $scope.checkedAttach = {};
                        var showDialog = null;
                        $scope.item_count = 0;

                        function allow(type) {
                            if (!$scope.useType) {
                                return true;
                            } else {
                                return $scope.allTypes.indexOf(type) != -1;
                            }
                        }
                        $scope.chosedClass = function(attach) {
                            // console.log("attach",attach);
                            if (attach.media_id) {
                                return $scope.checkedAttach.media_id == attach.media_id;
                            }
                            if (attach.url) {
                                return $scope.checkedAttach.url == attach.url;
                            }

                        }

                        $scope.choseAttach = function() {
                            $scope.chosedStatus = $scope.chosedStatus ? $scope.chosedStatus : 'sucai';
                            $scope.checkedAttach = {};
                            console.error("xiaoxixiaoxi", $scope.chosedStatus);
                            if (!$scope.hideList) {
                                $scope.attachList().then(showPop);
                            } else {
                                showPop();
                            }
                        }
                        $scope.clickcheck = function(envet, one, type) {
                            if (!one) return;
                            $scope.checkedAttach = one;
                            if (type) {
                                $scope.setdata();
                                showDialog.hide();
                                rmbdbg();
                            }
                        }

                        $scope.setdata = function() {
                                console.error(" $scope.dhfNgModel", $scope.dhfNgModel, $scope.checkedAttach, $scope.setback);
                                $timeout(function() {
                                    if ($scope.checkedAttach) {

                                        $scope.dhfNgModel = $scope.checkedAttach.url;
                                    }

                                    if ($scope.setback) {
                                        var attach = $scope.datatype ? $scope.checkedAttach : $scope.dhfNgModel;
                                        $scope.setback({
                                            attach: attach
                                        });
                                    }
                                    // rmAlert();

                                });
                            }
                            //
                        $scope.getdata = function(data) {
                            // console.error("url", $scope.chosedStatus, $scope.data);
                            if (data.value !== $scope.chosedStatus) {
                                $scope.chosedStatus = data.value;
                            }
                            $scope.getlist();
                        }
                        $scope.getlist = function(url) {
                            // console.error("url", $scope.chosedStatus);
                            $scope.attachs = [];
                            if ($scope.chosedStatus === 'sucai') {
                                $scope.attachList();
                            }
                            if ($scope.chosedStatus === 'xiaoxi') {
                                $scope.attachs = sessionService.get($scope.wxappid + "wxurl");
                                $scope.itemsTotal = 0;
                            }

                            if ($scope.stype) {
                                $scope.setback({
                                    url: url
                                });
                                showDialog.hide();
                            }
                            console.error("$scope.attachs", $scope.attachs, $scope.chosedStatus);
                        }

                        function showPop() {
                            showDialog = $.alert({
                                backdrop: 'static',
                                keyboard: true,
                                title: '<span>{{title | translate}}</span>',
                                body: $templateCache.get("views/directives.wxgzhurlattachment.html"),
                                okBtn: '{{"ok" | translate}}',
                                closeBtn: true,
                                transition: true,
                                // hasfoot: false,
                                width: '880px',
                                show: function(e) {
                                    $compile($(e.currentTarget).contents())($scope);
                                    return true;
                                },
                                okHide: function(e) {
                                    $scope.setdata();
                                    // rmAlert();
                                },
                            });
                        }

                        $scope.attachList = function(pageNo) {
                            var offset = $scope.item_count ? $scope.item_count : 0;
                            if (pageNo == 1 || !pageNo) {
                                offset = 0;
                            }

                            $scope.address = {
                                "type": "image",
                                "offset": offset,
                                "count": $scope.pageSize ? $scope.pageSize : 10
                            }
                            if ($scope.chosedStatus != 'sucai') {
                                $scope.address.type = $scope.chosedStatus;
                            }

                            return dataService.wxproxy($scope.wxappid, 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=TOKEN', 'POST', $scope.address).then(function(result) {
                                console.error("result", result);
                                $scope.attachs = result.item;
                                $scope.item_count = result.item_count;
                                $scope.itemsTotal = result.total_count;
                            });
                        }
                    }
                ],
                link: function(scope, element, attrs, ctrl) {
                    scope.class = attrs.xclass;
                }
            }
        })
        .run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.kficon.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive('kfIcon', function() {
            return {
                restrict: 'E',
                template: "<a href='javascript:void(0);' class='sui-btn btn-small btn-primary' ng-click='choseAttach();'>选择图标</a>",
                scope: {
                    ngModel: '=', //绑定的model
                    type: '=', //绑定的model
                },

                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout) {
                        // console.error("dddddddddddddd");
                        $scope.dfary = [
                            { "id": 1, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2w3kgc8DH8KJjSszcXXbDTFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 2, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2xSUEc46I8KJjy0FgXXXXzVXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 3, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2cM.jc_TI8KJjSsphXXcFppXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 4, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2JNssc22H8KJjy0FcXXaDlFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 5, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2rYglc0zJ8KJjSspkXXbF7VXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 6, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2EB3yc9_I8KJjy0FoXXaFnVXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 7, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2Fscuc0rJ8KJjSspaXXXuKpXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 8, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2_r.uc0rJ8KJjSspaXXXuKpXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 9, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2EhfFaRfM8KJjSZFOXXXr5XXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 10, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB28CzBX6gy_uJjSZJnXXbuOXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 11, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2lBoFc_nI8KJjy0FfXXcdoVXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 12, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2lofPaFYM8KJjSZFuXXcf7FXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 13, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2VyUjc0bJ8KJjy1zjXXaqapXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 14, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2mqcAc3vD8KJjy0FlXXagBFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 15, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2jGkLc3DD8KJjy0FdXXcjvXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 16, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2vQUGc6nD8KJjSspbXXbbEXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 17, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2ut.zc26H8KJjy0FjXXaXepXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 18, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2HPgycZbI8KJjy1zdXXbe1VXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 19, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB29KZFc2DH8KJjy1XcXXcpdXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 20, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2qB.kc8fH8KJjy1XbXXbLdXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 21, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2Ykkkc0fJ8KJjy0FeXXXKEXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 22, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2N5Qjc0bJ8KJjy1zjXXaqapXa-20841398.png20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 23, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2iJsBc4PI8KJjSspfXXcCFXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 24, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2Xyoyc3LD8KJjSszeXXaGRpXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 25, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2P7MGc6nD8KJjSspbXXbbEXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 26, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2JAMGc6nD8KJjSspbXXbbEXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 27, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB21xHSaJHO8KJjSZFHXXbWJFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 28, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2hL6QaFTM8KJjSZFlXXaO8FXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                        ];
                        $scope.xiaoxi = [
                            { "id": 1, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2P_Ulc46I8KJjSszfXXaZVXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 2, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2pCwyc3LD8KJjSszeXXaGRpXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 3, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2jKkHcY_I8KJjy1XaXXbsxpXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 4, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB27tbCX7fb_uJkSmFPXXcrCFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 5, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2nK7lc0zJ8KJjSspkXXbF7VXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 6, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2WeYCX7fb_uJkHFqDXXXVIVXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 7, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2uMczc0nJ8KJjSszdXXaxuFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 8, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2VwQmc_nI8KJjSszbXXb4KFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 9, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2bEgjc3vD8KJjSsplXXaIEFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 10, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2N0.Lc3DD8KJjy0FdXXcjvXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 11, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2X2.zc0nJ8KJjSszdXXaxuFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 12, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2nAUjc_TI8KJjSsphXXcFppXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 13, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2usAqc8HH8KJjy0FbXXcqlpXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 14, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2iCMxc4rI8KJjy0FpXXb5hVXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 15, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2dVZzc9_I8KJjy0FoXXaFnVXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 16, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2LFUzc9_I8KJjy0FoXXaFnVXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 17, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2nVK3b63z9KJjy0FmXXXiwXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 18, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2RgPMaLjM8KJjSZFyXXXdzVXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 19, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2omIjc0bJ8KJjy1zjXXaqapXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 20, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB22A7sc22H8KJjy0FcXXaDlFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 21, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2A03Lc3DD8KJjy0FdXXcjvXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 22, "path": "https://img.alicdn.com/imgextra/i1/20841398/TB2PPgvc8DH8KJjSspnXXbNAVXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 23, "path": "https://img.alicdn.com/imgextra/i2/20841398/TB2I63gc8DH8KJjSszcXXbDTFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 24, "path": "https://img.alicdn.com/imgextra/i4/20841398/TB2tMnAX6gy_uJjSZK9XXXvlFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 25, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2HbvQaFTM8KJjSZFAXXaexXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 26, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2yVG3b63z9KJjy0FmXXXiwXXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 27, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2QvZzc0nJ8KJjSszdXXaxuFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 28, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2K1szc8DH8KJjy1zeXXXjepXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                            { "id": 29, "path": "https://img.alicdn.com/imgextra/i3/20841398/TB2E0UAc3vD8KJjy0FlXXagBFXa-20841398.png", "original_name": "xx.png", "mime": "image/jpg", },
                        ];
                        if ($scope.type == 1) {
                            $scope.attach = clone($scope.dfary);
                        } else {
                            $scope.attach = clone($scope.xiaoxi);
                        }
                        $scope.choseAttach = function() {
                            showPop();
                        }

                        $scope.chosedClass = function(attach) {
                            console.log("attach", attach);
                            if (attach) {
                                return $scope.checkedAttach == attach;
                            } else {
                                return;
                            }
                        }

                        $scope.clickcheck = function(envet, one, type) {
                            if (!one) return;
                            $scope.checkedAttach = one;
                            if (type) {
                                $scope.setdata();
                                rmAlert();
                            }
                        }

                        $scope.setdata = function() {
                            $timeout(function() {
                                $scope.ngModel = $scope.checkedAttach.path;
                            });
                        }

                        function showPop() {
                            $.alert({
                                backdrop: 'static',
                                keyboard: true,
                                title: '<span>{{title | translate}}</span>',
                                body: $templateCache.get("views/directives.kficon.html"),
                                okBtn: '{{"ok" | translate}}',
                                closeBtn: true,
                                transition: true,
                                // hasfoot: false,
                                width: '880px',
                                show: function(e) {
                                    $compile($(e.currentTarget).contents())($scope);
                                    return true;
                                },
                                okHide: function(e) {
                                    $scope.setdata();
                                    rmAlert();
                                },
                            });
                        }

                    }
                ],
                link: function(scope, element, attrs, ctrl) {
                    scope.class = attrs.xclass;
                }
            }
        })
        .directive('wxattachmentlist', function() {
            return {
                restrict: 'E',
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                    wxappid: "=",
                    mediaid: "=",
                },
                templateUrl: "views/directives.wxattachent.list.html",
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout) {
                        $scope.initData = function() {
                            var qeury = {
                                "authorizer_appid": $scope.wxappid,
                                "media_id": $scope.mediaid,
                                base64: true,
                            };
                            dataService.materialone(qeury).then(function(one) {
                                console.error("one", one);
                                if (one.length > 100) {
                                    $scope.tmpNgModel = [{
                                        wxappid: $scope.wxappid,
                                        path: "data:image/png;base64," + one,
                                        media_id: $scope.mediaid,
                                        // attach_name:"image"
                                    }];
                                } else {
                                    console.log("数据获取失败");
                                }
                            });
                        }
                    }
                ],
                link: function(scope, element, attrs, ctrl) {
                    ctrl.$render = function() {
                        if (ctrl.$viewValue) {
                            scope.tmpNgModel = ctrl.$viewValue;
                            console.log("ctrl.$viewValue", ctrl.$viewValue);
                            scope.initData();
                        }
                    };
                    scope.$watch('mediaid', function(newValue, oldValue, scope) {
                        if (newValue) {
                            scope.initData();
                        }
                    });
                }
            }
        })
        .directive('kefuImg', function() {
            return {
                restrict: 'E',
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                    appid: '=',
                    type: '@',
                    applyType: '@',
                },
                templateUrl: "views/directives.kefuimg.html",
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'helper',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, helper) {
                        // console.error("$scope.appid", $scope.appid, $scope.ngModel);

                        $scope.initData = function() {
                            console.error("$scope.ngModel", $scope.ngModel);
                            $scope.getOne();
                        }

                        $scope.getOne = function(attach) {
                            if ($scope.ngModel || attach) {
                                // console.error("$scope.appid", $scope.appid, $scope.ngModel, );
                                var query = {};
                                if ($scope.ngModel) {
                                    // console.error("$scope.appid", query);
                                    query = { "mate_simu_task_id": $scope.ngModel, "apply_type": $scope.appid + $scope.applyType };
                                }
                                if (attach) {
                                    query = { "app_id": $scope.appid, "apply_type": $scope.appid + $scope.applyType };

                                }
                                // console.error("$scope.appid", query, $scope.ngMode);
                                return dataService.simutaskGetOne({ query: query }).then(function(result) {
                                    if (result) {
                                        $scope.mate_simu_task_id = result.mate_simu_task_id;
                                        $scope.imgurl = result.local_url;
                                        return $scope.mate_simu_task_id;
                                    } else {
                                        return dataService.promise();
                                    }
                                });
                            }
                        }

                        //回调添加数据
                        $scope.setback = function(attach) {
                            //查询数据 
                            $scope.getOne(attach).then(function(data) {
                                // console.error("datadatadata.appid", data, $scope.imgurl, $scope.mate_simu_task_id);
                                $scope.imgurl = attach;
                                if ($scope.mate_simu_task_id) {
                                    //有值就删除数据
                                    $scope.delData().then(function(data) {
                                        if (data) {
                                            $scope.AddData(attach);
                                        }
                                    })
                                } else {
                                    $scope.AddData(attach);
                                }
                            });
                        }

                        //添加数据
                        $scope.AddData = function(attach) {
                            var query = { "app_id": $scope.appid, "apply_type": $scope.appid + $scope.applyType, "local_url": attach };
                            dataService.simutaskAdd(query).then(function(result) {
                                if (!result.Msg) {
                                    $scope.ngModel = $scope.type ? result.local_url : result.mate_simu_task_id;
                                } else {
                                    helper.myAlert("api error：" + result.Msg);
                                }
                            });
                        }

                        //删除数据
                        $scope.delData = function() {
                            var query = { "mate_simu_task_id": $scope.mate_simu_task_id };
                            return dataService.simutaskDel(query).then(function(result) {
                                if (!result.Msg) {
                                    return true;
                                } else {
                                    helper.myAlert("error：" + result.Msg);
                                }
                            });

                        }

                        $scope.initData();
                    }
                ],
                link: function(scope, element, attrs, ctrl) {

                }
            }
        })
        .directive('wxgzAttachment', function() {
            return {
                restrict: 'E',
                template: "<a href='javascript:void(0);' class='{{class}}' ng-click='choseAttach();'>{{title|translate}}</a>",
                scope: {
                    wxappid: '=', //小程序id
                    // ownerType: '@', //所属类型：item、stock等
                    // subOwnerId: '=', //所属子对象id
                    dhfNgModel: '=', //绑定的model
                    xtype: '@', //返回类型: url=返回附件url地址，obj=返回附件对象
                    mult: "@", //是否允许多选
                    title: "@", //按钮文字
                    setback: "&", //回调函数
                    hideList: "@", //是否隐藏列表
                    useType: "@", //选择使用文件类型如图片为image
                    stype: "@",
                },

                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout) {
                        $scope.allTypes = $scope.useType ? $scope.useType.split(",") : [];
                        $scope.checkedAttach = {};

                        function allow(type) {
                            if (!$scope.useType) {
                                return true;
                            } else {
                                return $scope.allTypes.indexOf(type) != -1;
                            }
                        }
                        $scope.chosedClass = function(attach) {
                            // console.log("attach",attach);
                            return $scope.checkedAttach.media_id == attach.media_id;
                        }

                        $scope.choseAttach = function() {
                            if (!$scope.hideList) {
                                $scope.attachList().then(showPop);
                            } else {
                                showPop();
                            }
                        }

                        // $scope.title = $scope.title || "attachment";

                        $scope.clickcheck = function(envet, one, type) {
                            if (!one) return;
                            $scope.checkedAttach = one;
                            if (type) {
                                $scope.setdata();

                            }
                        }

                        $scope.setdata = function() {
                            console.error(" $scope.dhfNgModel", $scope.dhfNgModel);
                            $timeout(function() {
                                if ($scope.checkedAttach && $scope.xtype == 'mid') {
                                    $scope.dhfNgModel = $scope.checkedAttach.media_id;
                                } else {
                                    $scope.dhfNgModel = $scope.checkedAttach;
                                }
                                if ($scope.setback) {
                                    $scope.setback({
                                        attach: $scope.dhfNgModel
                                    });
                                }
                                rmAlert();
                            });
                        }

                        function showPop() {
                            $.alert({
                                backdrop: 'static',
                                keyboard: true,
                                title: '<span>{{title | translate}}</span>',
                                body: $templateCache.get("views/directives.wxgzattachment.html"),
                                okBtn: '{{"ok" | translate}}',
                                closeBtn: true,
                                transition: true,
                                // hasfoot: false,
                                width: '880px',
                                show: function(e) {
                                    $compile($(e.currentTarget).contents())($scope);
                                    return true;
                                },
                                okHide: function(e) {
                                    $scope.setdata();
                                    // rmAlert();
                                },
                            });
                        }

                        $scope.attachList = function(pageNo) {
                            var query = {};
                            if ($scope.wxappid) {
                                query.app_id = $scope.wxappid
                            }

                            return dataService.materialGet({ query: query }).then(function(list) {
                                $scope.attachs = list.materialRecords;
                                console.log($scope.attachs)
                                $scope.itemsTotal = list.total_count;
                            });
                        }
                    }
                ],
                link: function(scope, element, attrs, ctrl) {
                    scope.class = attrs.xclass;
                }
            }
        })
})();